package trabalho.doo3.j2me.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 *
 * @author Matheus
 */
public class Usuario {

    private String id;
    private String login;
    private String senha;
    private static final String RMSSTORE = "RMSUSUARIO";
    private RecordStore recordStore;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getSenha() {
        return senha;
    }

    public void setSenha(String senha) {
        this.senha = senha;
    }

    public byte[] getBytes() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        dos.writeUTF(id);
        byte[] ret = baos.toByteArray();
        dos.close();
        baos.close();
        return ret;
    }

    public void setBytes(byte[] valores) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(valores);
        DataInputStream dis = new DataInputStream(bais);
        this.id = dis.readUTF();
        dis.close();
        bais.close();
    }

    public void open() throws RecordStoreException {
        recordStore = RecordStore.openRecordStore(RMSSTORE, true);
    }

    public void insert(String usuario) throws IOException, RecordStoreException {
        byte[] registroBytes = usuario.getBytes();
        int ok = recordStore.addRecord(registroBytes, 0, registroBytes.length);
    }

    public void close() throws RecordStoreNotOpenException, RecordStoreException {
        recordStore.closeRecordStore();
    }

    public void clear() throws RecordStoreException {
        RecordStore.deleteRecordStore(RMSSTORE);
    }

    public Vector todos() throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, IOException {
        Vector v = new Vector();
        RecordEnumeration re = recordStore.enumerateRecords(null, null, false);
        while (re.hasNextElement()) {
            Usuario u = new Usuario();
            u.setId(String.valueOf(re.nextRecordId()));
            u.setBytes(recordStore.getRecord(Integer.parseInt(u.getId())));
            v.addElement(u);
        }
        return v;
    }
}
